#include"friendmodel.hpp"
#include"CommonConnectionPool.hpp"

#include<mymuduo/Logger.h>

bool FriendModel::insert(int userid, int friendid){
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "insert into Friend values(%d, %d)", userid, friendid);
    // 从连接池中获取一个mysql连接
    ConnectionPool *sqlConnPool = ConnectionPool::getConnectionPool();
    auto sqlConn = sqlConnPool->getConnection();
    //执行操作
    bool state = sqlConn->update(sql);
    if(state){
        return true;
    }
    return false;
}

//返回用户好友列表
vector<vector<string>> FriendModel::query(int userid){
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "select a.id, a.name, a.state from User a inner join Friend b on a.id = b.friendid where b.userid = %d", userid);
    // 从连接池中获取一个mysql连接
    ConnectionPool *sqlConnPool = ConnectionPool::getConnectionPool();
    auto sqlConn = sqlConnPool->getConnection();

    //执行查询操作
    vector<vector<string>> vec;
    MYSQL_RES* res = sqlConn->query(sql);
    if(res){
        MYSQL_ROW row;
        while((row = mysql_fetch_row(res)) != nullptr){
            vec.emplace_back(vector<string>{row[0], row[1], row[2]});
        }
    }
    mysql_free_result(res);
    return vec;
}